<?php

namespace app\api\middleware;

use app\common\model\Rule;
use think\facade\Db;
use think\facade\Request;

/**
 * 登录拦截器
 */

class Auth {
    public function handle($request, \Closure $next) {

        $token = Request::header("token");
        $userType = Request::header("userType"); // 1为管理后台用户，2为普通用户

        $userInfo = checkToken($token);


        if ($userInfo["code"] !== 200) {
            abort(420, $userInfo["msg"]);
        }


        if($userType == 1){

            $uid = $userInfo["result"]->uid;
            $table =  Db::name("admin");

            $groupId = $table->where("uid",$uid)->value("group_id");

            $ruleIds = Db::name("group_rule")->where("group_id",$groupId)->column("rule_id");

            $ruleUrl = Db::name("rule")->where("is_menu",0)->where("id","in",$ruleIds)->column("url");

            $appName =  app('http')->getName();
            $pathinfo = $request->pathinfo();
            $rule = $appName .'/' .$pathinfo;

            if(!in_array($rule,$ruleUrl)){
                abort(400,"没有访问权限");
            };
        }
        return $next($request);
    }
}
